#include <stdbool.h>
#include <inttypes.h>
#include "crypt.h"
#include <rpc/des_crypt.h>
#include <string.h>

/*
 * 加密
 * PKCS5 padding模式
 */
bool des_encrypt(const char* pkey, void* data, uint32_t size, uint32_t* len)
{
	char		key[9]		= {0};
	int			ret;
	int			i;

	strncpy(key, pkey, 8);
	des_setparity(key);
	// PKCS5 填充模式
	*len = (size + 8) / 8 * 8;
	for(i = size; i < *len; i++)
	{
		((char *)data)[i] = (char)(*len - size);
	}
	// 加密
	ret = ecb_crypt(key, data, *len, DES_ENCRYPT);

	return (DESERR_NONE == ret || DESERR_NOHWDEVICE == ret);
}

/*
 * DES解密
 * PKCS5 padding
 */
bool des_decrypt(const char* pkey, void* data, uint32_t size, uint32_t* len)
{
	char		key[9]		= {0};
	int			ret;
	int			i;
	int			c;

	strncpy(key, pkey, 8);
	des_setparity(key);
	// 验证大小
	if( 0 != (size % 8) || 0 == size)
	{
		return false;
	}
	// 解密
	ret = ecb_crypt(key, data, size, DES_DECRYPT);
	// 验证返回
	if(DESERR_NONE != ret && DESERR_NOHWDEVICE != ret)
	{
		return false;
	}
	// 返回实际大小
	c = ((char*)data)[size - 1];
	if( c > 8 || c < 1 )
	{
		return false;
	}
	*len = size - c;
	// 验证DES是否正确
	for(i = size - 1; i >= (size - c); i--)
	{
		if( ((char*)data)[i] != c)
		{
			return false;
		}
	}
	
	return true;
}

